import { CategoryApi } from '@/services/cms/CmsController';
import { DeleteFilled, DeleteOutlined, EditOutlined, PlusOutlined } from '@ant-design/icons';
import { ModalForm, PageContainer, PageLoading, ProFormSwitch, ProFormText, ProFormTextArea, ProFormTreeSelect } from '@ant-design/pro-components';
import { Access, request, useAccess, useRequest } from '@umijs/max';
import { Button, Flex, Form, message, Popconfirm, Space, Tree, Typography } from 'antd';
import { useEffect, useMemo, useState } from 'react';


const Settings: React.FC<{
    data: Cms.Category | null;
    onClose?: () => void;
    onFinish?: (data?: { id: number }) => void;
}> = ({ data, onClose, onFinish }) => {
    const [form] = Form.useForm<Cms.Category>();

    let { loading: fetching, run: run2 } = useRequest(CategoryApi.fetch, {
        throwOnError: true,
        manual: true,
        onSuccess: form.setFieldsValue
    });

    useEffect(() => { data?.id && run2(data.id) }, [data])

    let { loading: submiting, run: submit } = useRequest((d) => {
        if (data?.id) {
            return CategoryApi.update(data.id, { ...d, status: d.status ? 1 : 0 })
        } else {
            return CategoryApi.create({ ...d, status: d.status ? 1 : 0 })
        }
    },
        {
            manual: true,
            onError: () => {
                message.error('操作失败');
            },
            onSuccess(data, params) {
                message.success('操作成功');
                onFinish && onFinish(data)
                onClose && onClose()
            },
        })

    return <ModalForm<Cms.Category> title={data?.id ? "编辑" : "新增"} open={data != null} form={form} width={500} autoFocusFirstInput
        loading={submiting} submitTimeout={2000}
        onFinish={submit}
        modalProps={{
            destroyOnClose: true,
            onCancel: onClose,
        }}
    >
        {fetching ? <PageLoading></PageLoading> : <>
            <ProFormText name="name" label="名称" required />
            <ProFormTreeSelect request={CategoryApi.list} name="p_id" label="上级分类" placeholder="请选择上级分类"
                fieldProps={{
                    fieldNames: {
                        label: 'name',
                        value: 'id',
                    },
                }}
            />
            <ProFormText name="icon" label="图标" />
            <ProFormSwitch name="status" label="状态" initialValue={true} />
            <ProFormTextArea name="description" label="描述" />
        </>}
    </ModalForm>
}

const HomePage: React.FC = () => {
    const access = useAccess()
    const { data, run: loadCategory } = useRequest(CategoryApi.list, {
        initialData: [],
        onSuccess: (d) => {

        }
    })
    const { run: update } = useRequest(CategoryApi.update, {
        manual: true,
        onError() { loadCategory() },
        onSuccess(data, params) { loadCategory() },
    })
    const { run: del_category } = useRequest(CategoryApi.delete, {
        manual: true,
        onError() { loadCategory() },
        onSuccess(data, params) { loadCategory() },
    })

    const [editData, setEditData] = useState<Cms.Category | null>(null)
    const expandedKeys = useMemo(() => {
        let res: number[] = []
        let lo = (ds: Cms.Category[]) => {
            for (let i = 0; i < ds.length; i++) {
                const d = ds[i];
                res.push(d.id || 0)
                lo(d.children || [])
            }
        };
        lo(data || [])
        return res
    }, [data])
    return (
        <PageContainer ghost breadcrumbRender={false} extra={access.cms_category_edit && <Button onClick={() => setEditData({ name: "" })} icon={<PlusOutlined />}>新增</Button>}>
            <Settings data={editData} onClose={() => setEditData(null)} onFinish={() => loadCategory()}></Settings>
            <Tree<Cms.Category>
                expandedKeys={expandedKeys}
                expandAction={false}
                // switcherIcon={<></>}
                draggable={access.cms_category_edit}
                treeData={data} fieldNames={{ title: "name", key: "id" }}
                titleRender={(d) =>
                    <Flex justify='space-between' align='center' style={{ padding: 4 }}>
                        <Typography.Text>{d.name}</Typography.Text>
                        <Access accessible={access.cms_category_edit}  >
                            <Space>
                                <Button size='small' onClick={() => setEditData(d)} type='link' icon={<EditOutlined />}></Button>
                                <Popconfirm
                                    title="删除分类"
                                    description="删除此分类之后，对应文章的关联将被解除。该操作不可恢复。?"
                                    onConfirm={() => d.id && del_category(d.id)}
                                >
                                    <Button size='small' type='link' danger icon={<DeleteOutlined />}></Button>
                                </Popconfirm>
                            </Space>
                        </Access>
                    </Flex>
                }
                blockNode
                defaultExpandAll={true}
                autoExpandParent
                onDrop={(info) => {
                    let drapNode = info.dragNode.id
                    let node = info.node
                    let p_id = 0
                    let sort = 1;
                    if (!info.dropToGap) {
                        p_id = node.id || 0
                    } else {
                        p_id = node.p_id || 0
                    }
                    if (node.dragOverGapTop) {
                        sort = node.sort || 1
                    }
                    if (node.dragOverGapBottom) {
                        sort = (node.sort || 1) + 1
                    }
                    drapNode && update(drapNode, { p_id, sort })
                }}
            >

            </Tree>
        </PageContainer>
    );
};

export default HomePage;
